package com.zslc.foreignoption.util;

import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ShUtil {

    private static ExecutorService exec = Executors.newFixedThreadPool(50);



    public static boolean shHandel(String cmd) {
        try {
            System.out.println("执行命令 "+cmd);
            Process proc = Runtime.getRuntime().exec(cmd);
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }


    public static boolean shHandel1(String cmd) {
        try {
            String[] cmdd = {"/bin/bash", "-c", cmd};
            Process proc = Runtime.getRuntime().exec(cmdd);
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
    public static boolean shHandel0(String cmd) {
        try {
            String[] cmdd = {"sh", "-c", cmd};
            Process proc = Runtime.getRuntime().exec(cmdd);
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    public static boolean shHandel4(String cmd) {
        exec.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("执行命令 "+cmd);
                    String[] cmdd = { "/bin/bash", "-c", cmd };
                    Process proc = Runtime.getRuntime().exec(cmdd);
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
                    errorGobbler.start();
                    outputGobbler.start();
                    proc.waitFor();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        return true;
    }


    public static boolean shHandel(List<String> cmdList) {
        exec.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <cmdList.size() ; i++) {
                    String cmd =cmdList.get(i);
                    try {
                        System.out.println("执行命令 "+cmd);
                        Process proc = Runtime.getRuntime().exec(cmd);
                        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
                        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
                        errorGobbler.start();
                        outputGobbler.start();
                        proc.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            }
        });

        return true;
    }


    public static String getShHandel(String cmd,String filePath) {
        try {
            cmd="source /etc/profile.d/local.sh ;"+cmd+" "+filePath;
            System.out.println("执行命令 "+cmd+" ");

            String[] cmdA = {"/bin/bash", "-c", cmd};
            Process process = Runtime.getRuntime().exec(cmdA);
            LineNumberReader br = new LineNumberReader(new InputStreamReader(
                    process.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            System.out.println(sb.toString());

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getShHandel(String cmd) {
        try {
            System.out.println("执行命令 "+cmd);

            String[] cmdA = {"/bin/sh", "-c", cmd};
            Process process = Runtime.getRuntime().exec(cmdA);

            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");
            errorGobbler.start();
            LineNumberReader br = new LineNumberReader(new InputStreamReader(
                    process.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            System.out.println(sb.toString());
            process.waitFor();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getBAShHandel(String cmd) {
        try {
            System.out.println("执行命令 "+cmd);

            String[] cmdA = {"/bin/bash", "-c", cmd};
            Process process = Runtime.getRuntime().exec(cmdA);

            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");
            errorGobbler.start();
            LineNumberReader br = new LineNumberReader(new InputStreamReader(
                    process.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            System.out.println(sb.toString());
            process.waitFor();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return 删除成功返回true, 失败返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println("删除文件成功：" + fileName);
            return true;
        } else {
            System.out.println("删除文件失败：" + fileName);
            return false;
        }
    }

    /**
     * 删除文件夹
     * 删除文件夹需要把包含的文件及文件夹先删除，才能成功
     *
     * @param directory 文件夹名
     * @return 删除成功返回true, 失败返回false
     */
    public static boolean deleteDirectory(String directory) {
        // directory不以文件分隔符（/或\）结尾时，自动添加文件分隔符，不同系统下File.separator方法会自动添加相应的分隔符
        if (!directory.endsWith(File.separator)) {
            directory = directory + File.separator;
        }
        File directoryFile = new File(directory);
        // 判断directory对应的文件是否存在，或者是否是一个文件夹
        if (!directoryFile.exists() || !directoryFile.isDirectory()) {
            System.out.println("文件夹删除失败，文件夹不存在" + directory);
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文件和文件夹
        File[] files = directoryFile.listFiles();
        for (int i = 0; i < files.length; i++) {  // 循环删除所有的子文件及子文件夹
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            } else {  // 删除子文件夹
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            System.out.println("删除失败");
            return false;
        }
        // 最后删除当前文件夹
        if (directoryFile.delete()) {
            System.out.println("删除成功：" + directory);
            return true;
        } else {
            System.out.println("删除失败：" + directory);
            return false;
        }
    }
}
